﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Linq.Expressions;
using Newtonsoft.Json;
using OA.Core;
using OA.Model;
using OA.BLL;
using Microsoft.Extensions.Caching.Memory;
using OA.Web.Code;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OA.Model.DB;
using OA.Core.Helper;
using Z.EntityFramework.Plus;
using OA.Core.Model;

namespace OA.Web.Areas.Admin.Controllers
{
    public class TableInfoController : BaseAdminController
    {
        private IMemoryCache _cache;
        public TableInfoController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
        }

        public IActionResult Index()
        {            
            return View();
        }

        public IActionResult GetData(string keyword, int page = 1, int limit = 20)
        {
            Expression<Func<TableInfo, bool>> where = m => true;
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                where = m => (m.Name.Contains(keyword));
            }
            PageList<SimpleTableInfo> list = this.GetPageList<TableInfo, SimpleTableInfo>(where, page, limit, SimpleTableInfo.Map);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.RowCount,
                data = list.List
            };
            return Json(result);
        }

        [HttpGet]
        public IActionResult Create()
        {
            
            return View(new TableInfo());
        }




        [HttpPost]
        public IActionResult Create(TableInfo model)
        {
            BaseResult baseResult = new BaseResult();
            if (!ModelState.IsValid)
            {
                baseResult.Msg = this.GetModelStateError(ModelState);
                baseResult.State = 400;
                return Json(baseResult);
            }
            else
            {
                this.AddInfo<TableInfo>(model);
                baseResult.Msg = "表格添加成功！";
                return Json(baseResult);

            }

        }


        [HttpGet]
        public IActionResult Delete(int id)
        {
            Expression<Func<TableInfo, bool>> where = m => m.ID == id;
            this.Delete<TableInfo>(where);
            return Json(new { State = 200, Msg = "" });
        }

        [HttpGet]
        public IActionResult Edit(int id)
        {
            TableInfo info = this.GetInfo<TableInfo>(id);
            if (info == null)
            {
                return Redirect("/Admin/Home/Info?msg=" + System.Web.HttpUtility.UrlEncode("沒有找到该表格信息", Encoding.UTF8));
            }
            ViewBag.CustomForm = this.dbContextFactory.DbContext.CustomForm.Select(m => new ListItem() { Value = m.ID.ToString(), Text = m.Name }).ToList();
            return View(info);
        }

      

        [HttpPost]
        public IActionResult ShowPreview(string infos)
        {
            List<ExtendField> list = JsonHelper.DeserializeList<ExtendField>(infos);
            return View(list);
        }


        [HttpPost]
        public IActionResult SaveTable(int id, string infos)
        {
            BaseResult baseResult = new BaseResult();
            List<ExtendField> list = JsonHelper.DeserializeList<ExtendField>(infos);
            if (list.Count == 0)
            {
                baseResult.State = 400;
                baseResult.Msg = "空的表格不能保存";
            }
            else
            {
                var jisuans = list.Where(m => !string.IsNullOrWhiteSpace(m.Values) && (m.Type == 68 || m.Type == 69)).ToList();
                if(jisuans.Count>0)
                {
                    Dictionary<string, string> dicReplace = new Dictionary<string, string>();
                    foreach (var item in list)
                    {
                        if(item.Type==2||item.Type==21)
                        {
                            dicReplace.Add(item.ParentName + "." + item.Name, item.Attribute);
                        }
                    }
                    foreach (var item in jisuans)
                    {
                        foreach (var key in dicReplace.Keys)
                        {
                            item.Values = item.Values.Replace(key, dicReplace[key]);
                        }
                    }
                }                
                this.dbContextFactory.DbContext.TableInfo.Where(m => m.ID == id).Update(m => new TableInfo() { ConfigContent = JsonHelper.SerializeObject(list) });
            }
            return Json(baseResult);
        }


    }
}